<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>路由元信息</title>
    <script src="https://cdn.bootcss.com/vue/2.4.2/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
    <div id="app">
        <h1>Hello App</h1>
        <p>
            <router-link to="/login">Go to Login</router-link>
            <router-link to="/foo">Go to Foo</router-link>
            <router-link to="/bar/1">Go to Bar 1</router-link>
            <router-link to="/bar/2">Go to Bar 2</router-link>
        </p>

        <router-view></router-view>
    </div>

<script>
    const Login = {template : '<div>login</div>'}
    const Foo = {template : '<div>foo</div>'}
    const Bar = {template : '<div>bar</div>'}

    const routes = [
        {path : '/login', component : Login},
        {
            path : '/foo',
            component : Foo,
            created(){
                console.log('ccccccccccccc')
            }
        },
        {path : '/bar/:id', component : Bar, meta: { requiresAuth: true }}
    ]

    const router = new VueRouter({
        routes
    });
    router.beforeEach((to, from, next) => {
        //使用这个方法可以检查是否有权限，没有权限跳转到登录页
        if (to.matched.some(record => record.meta.requiresAuth)) {
            // this route requires auth, check if logged in
            // if not, redirect to login page.
            if (to.params.id == 1) {
                next({
                    path: '/login',
                    query: { redirect: to.fullPath }
                })
            } else {
                next()
            }
        } else {
            next() // 确保一定要调用 next()
        }
    })

    const app = new Vue({
        router
    }).$mount("#app");
</script>
</body>
</html>
